const goods = require('../../api/goods')
const goodsCategory = goods.category
const goodsList = goods.goodsList
const course = require('../../api/course')
const courseCategory = course.category
const courseList = course.courseList
const { activityList } = require('../../api/activity')
const { API_OK } = require('../../utils/setting')

Page({
  data: {
    stickyTop: 0,
    activeSortIndex: 0,
    loading: false,
    title: '',
    subTitle: '',
    tabs: [],
    categoryId: 0,
    sortLabels: [
      { label: '综合', value: 'all', sort: false },
      { label: '销量', value: 'sales', sort: true, status: 0 },
      { label: '新品', value: 'new', sort: true, status: 0 },
      { label: '价格', value: 'price', sort: true, status: 0 }
    ],
    type: '',
    list: []
  },
  pageData: {
    page: 1,
    canLoadMore: true,
    listApi: null
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    this.setStickyTop()
    this.setData({ type: options.type })
    this.setPageData(options.type)
    options.type !== 'activity' && await this.getTabs()
    this.pageData.listApi()
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (!this.data.canLoadMore || this.data.loading) return
    this.pageData.page += 1
    this.pageData.listApi()
  },
  setStickyTop() {
    const {top, bottom} = wx.getMenuButtonBoundingClientRect()
    wx.getSystemInfo({
      success: ({statusBarHeight})=>{
        this.setData({ stickyTop: bottom + (top - statusBarHeight)})
      }
    })
  },
  setPageData(type) {
    if (type === 'hot' || type === 'credit') {
      this.pageData.listApi = this.getGoods
      this.setData({title: '全部商品', subTitle: '件商品'})
    } else if (type === 'course') {
      this.pageData.listApi = this.getCourse
      this.setData({title: '全部星球', subTitle: '个星球'})
    } else if (type === 'activity') {
      this.pageData.listApi = this.getActivity
      this.setData({title: '全部活动', subTitle: '个活动'})
    } else {
      this.pageData.listApi = this.getGoods
      this.setData({title: '全部周边', subTitle: '件商品'})
    }
  },
  /**
   * 切换分类
   */
  changeCategory({ detail }) {
    this.setData({ categoryId: detail.name, list: [] })
    this.pageData.page = 1
    this.pageData.canLoadMore = true
    this.pageData.listApi()
  },
  /**
   * 切换排序类型
   */
  changeActiveIndex({ detail }) {
    if (this.data.activeSortIndex === detail.index) return
    const lastIndexLabel = this.data.sortLabels[this.data.activeSortIndex]
    lastIndexLabel.sort && (lastIndexLabel.status = 0)
    this.setData({
      activeSortIndex: detail.index,
      sortLabels: this.data.sortLabels,
      list: []
    })
    this.pageData.page = 1
    this.pageData.canLoadMore = true
    this.pageData.listApi()
  },
  /**
   * 修改排序规则（升降序）
   */
  changeSortStatus({ detail }) {
    const target = this.data.sortLabels[detail.index]
    target.status = target.status === 0 ? 1 : 0
    this.setData({
      sortLabels: this.data.sortLabels,
      list: []
    })
    this.pageData.page = 1
    this.pageData.canLoadMore = true
    this.pageData.listApi()
  },
  /**
   * 获取分类
   */
  async getTabs() {
    return this.data.type === 'course' ? this.getCourseTabs() : this.getGoodsTabs()
  },
  /**
   * 获取商品分类
   */
  async getGoodsTabs() {
    const type = this.data.type === 'hot' ? 1 : this.data.type === 'credit' ? 2 : 3
    try {
      const res = await goodsCategory({
        data: {type},
        callback: wx.hideLoading
      })
      console.log('tabs: ', res)
      if (res.code === API_OK) {
        const tabs = res.data.list.map(tab => ({ id: tab.category_id, label: tab.name }))
        const allText = this.data.type === 'hot' || this.data.type === 'credit'
          ? '全部商品'
          : '全部周边'
        tabs.unshift({id: 0, label: allText})
        this.setData({ tabs })
      }
    } catch(err) {
      console.warn(err)
    }
  },
  async getCourseTabs() {
    try {
      const res = await courseCategory({ callback: wx.hideLoading })
      console.log('课程tab: ', res)
      if (res.code === API_OK) {
        const tabs = res.data.list.map(item => ({ id: item.cate_course_id, label: item.cate_course_name }))
        tabs.unshift({id: 0, label: '全部'})
        this.setData({ tabs })
      }
    } catch(err) {
      console.warn(err)
    }
  },
  /**
   * 获取商品列表
   */
  async getGoods() {
    this.setData({ loading: true })
    const type = this.data.type === 'hot' ? 1 : this.data.type === 'credit' ? 2 : 3
    try {
      const res = await goodsList({
        data: {
          type,
          category_id: this.data.categoryId,
          keywords: '',
          is_total: 0,
          is_sales: this.data.sortLabels[1].status,
          is_new: this.data.sortLabels[2].status,
          is_price: this.data.sortLabels[3].status,
          p: this.pageData.page
        }
      })
      // console.log('商品列表：', res)
      if (res.code === API_OK) {
        this.pageData.canLoadMore = res.data.list.current_page < res.data.list.last_page
        this.setData({
          loading: false,
          list: res.data.list.data.map(goods => {
            return {
              id: goods.goods_id,
              image: (goods.image && goods.image.length) ? goods.image[0].file_path : '',
              name: goods.goods_name,
              price: goods.goods_price,
              credit: this.data.type === 'credit' ? goods.score_deduct * 1 : undefined
            }
          })
        })
      }
    } catch(err) {
      console.warn(err)
    }
  },
  /**
   * 获取活动列表
   */
  async getActivity() {
    this.setData({ loading: true })
    try {
      const res = await activityList({ data: { paginate: 15, page: this.pageData.page }})
      console.log('活动列表: ', res)
      if (res.code === API_OK) {
        this.pageData.canLoadMore = res.data.current_page < res.data.last_page
        this.setData({
          loading: false,
          list: res.data.data.map(item => {
            return {
              id: item.id,
              image: item.images.length && item.images[0].file_path,
              name: item.title,
              address: item.address,
              time: item.start_end_time
            }
          })
        })
      }
    } catch(err) {
      console.warn(err)
    }
  },
  /**
   * 获取课程列表
   */
  async getCourse() {
    this.setData({ loading: true })
    try {
      const res = await courseList({
        data: {
          category_id: this.data.categoryId,
          sortType: this.data.sortLabels[this.data.activeSortIndex].value,
          sortPrice: this.data.sortLabels[this.data.activeSortIndex].status || 0,
          search: '',
          page: this.pageData.page,
          paginate: 15
        }
      })
      console.log('课程列表：', res)
      if (res.code === API_OK) {
        this.pageData.canLoadMore = res.data.current_page < res.data.last_page
        this.setData({
          loading: false,
          list: res.data.data.map(item => {
            return {
              id: item.courses_id,
              image: (item.image && item.image.length) && item.image[0].file_path,
              courseName: item.course_name,
              classHour: item.lessons_count,
              purchasedNum: item.sold_count,
              coursePrice: item.course_price
            }
          })
        })
      }
    } catch(err) {
      console.warn(err)
    }
  }
})
